package com.tiyende.credit.loop.ui.activity

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.CountDownTimer
import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.gms.auth.api.phone.SmsRetriever
import com.lib.common.adapter.CommonOnItemChildClickListener
import com.tiyende.credit.loop.R
import com.tiyende.credit.loop.base.app.TiyendeActivityStackManager
import com.tiyende.credit.loop.common.CommonActivity
import com.tiyende.credit.loop.databinding.TiyendeActivityCheckMobileBinding
import com.tiyende.credit.loop.event.TiyendeEventData
import com.tiyende.credit.loop.event.TiyendeEventPointType
import com.tiyende.credit.loop.ui.adapter.TiyendeCheckMobileTypeAdapter
import com.tiyende.credit.loop.ui.contract.IViewContract
import com.tiyende.credit.loop.ui.dialog.TiyendeCheckMobileSendCodeSuccessDialog
import com.tiyende.credit.loop.ui.dialog.TiyendeTipsDialog
import com.tiyende.credit.loop.ui.presenter.TiyendeCheckMobilePresenter
import com.tiyende.credit.loop.utils.TiyendeDensityUtil
import com.tiyende.credit.loop.utils.decoration.LinearSpacingItemDecoration
import com.tiyende.credit.loop.utils.helper.TiyendeProcessHelper
import com.tiyende.credit.loop.utils.log.TiyendeLogger
import com.tiyende.credit.loop.utils.receiver.TiyendeSmsBroadcastReceiver
import com.tiyende.credit.loop.utils.shared.TiyendeSharedHelper
import com.tiyende.credit.loop.utils.shared.TiyendeSharedKey
import com.tiyende.credit.loop.utils.track.TrackPointManager
import com.tiyende.credit.loop.weight.pickerview.builder.TimePickerBuilder
import com.tiyende.credit.loop.weight.pickerview.listener.OnTimeSelectListener
import com.tiyende.credit.loop.weight.pickerview.view.TimePickerView
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date

/**
 * TiyendeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/11 16:41
 * @Annotation：账号验证页面
 */
class TiyendeCheckMobileActivity: CommonActivity(), IViewContract.ITiyendeCheckMobileView{
//    lateinit var binding: TiyendeActivityCheckMobileBinding
    private var _binding: TiyendeActivityCheckMobileBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot access binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )

    var presenter: TiyendeCheckMobilePresenter? = null
    private var sendSuccessDialog: TiyendeCheckMobileSendCodeSuccessDialog? = null
    private var smsBroadcastReceiver: TiyendeSmsBroadcastReceiver? = null

    private var checkTypeAdapter: TiyendeCheckMobileTypeAdapter? = null
    private val typeIconList = arrayListOf(R.mipmap.tiyende_check_mobile_send_sms_icon,R.mipmap.tiyende_check_mobile_send_whatsapp_icon,R.mipmap.tiyende_check_mobile_send_telegram_icon,R.mipmap.tiyende_check_mobile_send_telegrambot_icon)
    private val typeTitleList = arrayListOf(R.string.tiyende_check_mobile_type_sms,R.string.tiyende_check_mobile_type_whatsapp,R.string.tiyende_check_mobile_type_telegram,R.string.tiyende_check_mobile_type_telegram_bot)
    private var isClickCheck = true

    private val SMS_CONSENT_REQUEST = 200
    var eventRemark = ""

    //等待时长
    private var countdownTimer: MyCountDownTimer? = null
    private var countdown = 60

    //需要选择出生日期
    private var pvStartDateView: TimePickerView? = null
    companion object {
        fun start(context: Context) {
            //当前栈顶是 手机号校验页面 不重复跳转
            if (TiyendeActivityStackManager.isCurrentActivity(TiyendeCheckMobileActivity::class.java)){
                return
            }
            val intent = Intent(context, TiyendeCheckMobileActivity::class.java)
            context.startActivity(intent)
        }
    }
    override fun getTiyendeRootView(): View {
        _binding = TiyendeActivityCheckMobileBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initTiyendeView() {
        eventRemark = "Check Mobile Page"
        setBackExit(true)
        setTiyendeTitleBarVisibility(View.VISIBLE)
        setTiyendeBackBtnVisibility(View.GONE)
        setTiyendeRightBtnRes(R.mipmap.tiyende_customer_white)
        setTiyendeTextTitleVisibility(View.GONE)

        initRefreshView()
        initTiyendeCheckMobileTypeListView()
        showChcekMobileTypeView(false)

        SmsRetriever.getClient(this).startSmsUserConsent(null)
        registerSMSBroadcastReceiver()
    }

    override fun initTiyendeListener() {
        //客服
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog(eventRemark)
            addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_CUSTOMER,eventRemark)
        }
        _binding?.editCode?.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                presenter?.let {
                    _binding?.btnSubmit?.isEnabled = it.getCheckNumberSelectType().isNotEmpty() && getTiyendeCheckMobileCode().isNotEmpty()
                }
            }
        })
        _binding?.editMobile?.addTextChangedListener(object : TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                _binding?.btnConfirm?.isEnabled = getTiyendeCheckMobile().isNotEmpty()
            }
        })

        _binding?.btnSend?.setOnClickListener {
            presenter?.let {
                if (it.getCheckNumberSelectType().isEmpty()){
                    return@setOnClickListener
                }
                it.sendCheckNumberWhatsAppCodeAction()
            }
        }

        _binding?.imgEdit?.setOnClickListener {
           showChcekMobileTypeView(true)
        }
        _binding?.btnConfirm?.setOnClickListener {
            if (getTiyendeCheckMobile().isEmpty()){
                return@setOnClickListener
            }
            binding.textMobile.text = getTiyendeCheckMobile()
            showChcekMobileTypeView(false)
        }
        //提交
        _binding?.btnSubmit?.setOnClickListener {
            presenter?.let {
                val checkType = it.getCheckNumberSelectType()
                if (checkType == "TGBOT"){
                    addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_VERIFICATION_CONTINUE,"${checkType}##${getTiyendeCheckMobile()}")
                    // TODO: 后置校验  continue 提交所有埋点
                    TrackPointManager.getInstance().manualReport()

                    it.loadTiyendeCheckLinkAction()
                    return@setOnClickListener
                }

                addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_VERIFICATION_CONTINUE,"${it.getCheckNumberSelectType()}##${getTiyendeCheckMobileCode()}##${getTiyendeCheckMobile()}")
                // TODO: 后置校验  continue 提交所有埋点
                TrackPointManager.getInstance().manualReport()
                if (getTiyendeCheckMobile().isEmpty() || getTiyendeCheckMobileCode().isEmpty()){
                    _binding?.btnSubmit?.isEnabled = false
                    return@setOnClickListener
                }
                it.onCheckNumberVerificationCodeAction()
            }
        }
    }

    @SuppressLint("SetTextI18n")
    override fun loadTiyendeData() {
        presenter = TiyendeCheckMobilePresenter(this)
        val zoneCode = TiyendeSharedHelper.queryTiyendeSharedString(TiyendeSharedKey.TIYENDE_TIMEZONE_CODE)
        val mobile = TiyendeSharedHelper.queryTiyendeSharedString(TiyendeSharedKey.TIYENDE_MOBILE)
        _binding?.textZoneCode?.text = "+$zoneCode"
        _binding?.textMobile?.text = mobile
        _binding?.editMobile?.setText(mobile)

        _binding?.btnSend?.text = getString(R.string.tiyende_button_send)
        _binding?.btnSend?.isEnabled = false
        isClickCheck = true

        if (TiyendeProcessHelper.isTiyendeAuthenticationCheckSMS()){
            val item = JSONObject()
            item.put("checkType","SMS")
            item.put("checkTypeIcon",typeIconList[0])
            item.put("checkTypeTitle",getString(typeTitleList[0]))
            item.put("isSelected",false)
            checkTypeAdapter?.addLastItem(item)
        }
        if (TiyendeProcessHelper.isTiyendeAuthenticationCheckWhatsApp()){
            val item = JSONObject()
            item.put("checkType","WHATSAPP")
            item.put("checkTypeIcon",typeIconList[1])
            item.put("checkTypeTitle",getString(typeTitleList[1]))
            item.put("isSelected",false)
            checkTypeAdapter?.addLastItem(item)
        }
        if (TiyendeProcessHelper.isTiyendeAuthenticationCheckTelegram()){
            val item = JSONObject()
            item.put("checkType","TELEGRAM")
            item.put("checkTypeIcon",typeIconList[2])
            item.put("checkTypeTitle",getString(typeTitleList[2]))
            item.put("isSelected",false)
            checkTypeAdapter?.addLastItem(item)
        }
        if (TiyendeProcessHelper.isTiyendeAuthenticationCheckTelegramBot()){
            val item = JSONObject()
            item.put("checkType","TGBOT")
            item.put("checkTypeIcon",typeIconList[3])
            item.put("checkTypeTitle",getString(typeTitleList[3]))
            item.put("isSelected",false)
            checkTypeAdapter?.addLastItem(item)
        }
        showDefaultCheckTypeView()
        showTiyendeCheckMobileTipsDialog()
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun initTiyendeCheckMobileTypeListView(){
        _binding?.rvCheckTypeListView?.setHasFixedSize(true)
        _binding?.rvCheckTypeListView?.isNestedScrollingEnabled = false
        _binding?.rvCheckTypeListView?.isFocusableInTouchMode = false //不需要焦点
        _binding?.rvCheckTypeListView?.layoutManager = LinearLayoutManager(this)
        checkTypeAdapter = TiyendeCheckMobileTypeAdapter(_binding?.rvCheckTypeListView)
        _binding?.rvCheckTypeListView?.adapter = checkTypeAdapter
        val leftDecoration = TiyendeDensityUtil.dp2px(12f)
        _binding?.rvCheckTypeListView?.addItemDecoration(LinearSpacingItemDecoration(0, 0,leftDecoration,leftDecoration))
        _binding?.rvCheckTypeListView?.itemAnimator = DefaultItemAnimator()
        checkTypeAdapter?.setOnItemChildClickListener(CommonOnItemChildClickListener { _, childView, position ->
            checkTypeAdapter?.let {
                val item = it.getItem(position)
                if (!isClickCheck || item.optBoolean("isSelected") || getTiyendeCheckMobile().isEmpty()){
                    return@CommonOnItemChildClickListener
                }
                if (childView.id == R.id.checkTypeLayout){
                    for (i in 0..< it.itemCount){
                        it.getItem(i)?.put("isSelected",false)
                    }
                    item.put("isSelected",true)
                    it.notifyDataSetChanged()
                    presenter?.setCheckNumberType(item.optString("checkType"),true)
                }
            }
        })
    }

    /**
     * 注册SMS广播接收
     */
    private fun registerSMSBroadcastReceiver(){
        // 2 register receiver
        val intentFilter = IntentFilter(SmsRetriever.SMS_RETRIEVED_ACTION)
        smsBroadcastReceiver = TiyendeSmsBroadcastReceiver {
            startActivityForResult(it, SMS_CONSENT_REQUEST)
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // Android 13 及以上版本使用 receiverFlags 参数
            registerReceiver(smsBroadcastReceiver, intentFilter, SmsRetriever.SEND_PERMISSION, null, Context.RECEIVER_EXPORTED)// 指定导出标志
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // Android 8.0 到 Android 12 版本使用带权限的 registerReceiver()
            registerReceiver(smsBroadcastReceiver, intentFilter, SmsRetriever.SEND_PERMISSION, null)
        } else {
            // Android 8.0 以下版本，只使用 receiver 和 intentFilter 参数
            registerReceiver(smsBroadcastReceiver, intentFilter)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == SMS_CONSENT_REQUEST) {
            if (resultCode == Activity.RESULT_OK && data != null) {
                // 读取短信内容
                val message = data.getStringExtra(SmsRetriever.EXTRA_SMS_MESSAGE)
                TiyendeLogger.e("Sms content: $message")

                // 提取otp
                val code = extractFirstNumber(message)
                TiyendeLogger.e("Sms code: $code")
                if (code != null){
                    _binding?.editCode?.setText(code)
                }
            } else {
                // 用户不同意或没收到待
                TiyendeLogger.e("User canceled or no message received")
            }
        }
    }

    /* 初始化刷新 */
    private fun initRefreshView() {
        _binding?.checkRefreshLayout?.setColorSchemeResources(R.color.theme,R.color.purple_500)
        _binding?.checkRefreshLayout?.setOnRefreshListener {
            publishEventData(TiyendeEventData(TiyendeEventData.TYPE.TIYENDE_PROCESS_REFRESH))
        }
    }

    /**
     * 获取手机号
     */
    override fun getTiyendeCheckMobile(): String {
        return _binding?.editMobile?.text.toString().trim()
    }

    /**
     * 获取验证码
     */
    override fun getTiyendeCheckMobileCode(): String {
        return _binding?.editCode?.text.toString().trim()
    }

    /**
     * 切换是否修改手机号View
     */
    private fun showChcekMobileTypeView(isEdit: Boolean){
        //是否允许修改手机号码
        if (!TiyendeProcessHelper.isTiyendeAuthenticationMobileEditFlag()){
            _binding?.showMobileLayout?.visibility = View.VISIBLE
            _binding?.imgEdit?.visibility = View.INVISIBLE
            _binding?.showEditLayout?.visibility = View.GONE
            return
        }
        when(isEdit){
            true -> {
                _binding?.showMobileLayout?.visibility = View.GONE
                _binding?.showEditLayout?.visibility = View.VISIBLE
                onShowSoftInput(_binding?.editMobile)
                _binding?.editMobile?.setSelection(getTiyendeCheckMobile().length)
            }
            else -> {
                _binding?.showMobileLayout?.visibility = View.VISIBLE
                _binding?.imgEdit?.visibility = View.VISIBLE
                _binding?.showEditLayout?.visibility = View.GONE
            }
        }
    }

    /**
     * 设置默认选中校验类型
     */
    private fun showDefaultCheckTypeView(){
        //设置默认选中第一个
        checkTypeAdapter?.let {
            if (it.itemCount > 0){
                val item = it.getItem(0)
                item.put("isSelected",true)
                it.notifyItemChanged(0)
                presenter?.setCheckNumberType(item.optString("checkType"),false)
            }
        }
    }

    /**
     * 切换校验类型
     */
    override fun showTiyendeCheckMobileType(type: String,isSubTrack: Boolean) {
        _binding?.btnSend?.isEnabled = true
        _binding?.btnSubmit?.isEnabled = getTiyendeCheckMobileCode().isNotEmpty()

        _binding?.textCheckCodeTitle?.visibility = View.VISIBLE
        _binding?.checkCodeLayout?.visibility = View.VISIBLE
        if (type == "TGBOT"){
            _binding?.textCheckCodeTitle?.visibility = View.GONE
            _binding?.checkCodeLayout?.visibility = View.GONE
            _binding?.btnSubmit?.isEnabled = true
        }

        //需要提交埋点
        if (isSubTrack){
            when(type){
                "SMS" -> {
                    addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_VERIFICATION_SMS)
                }
                "WHATSAPP" -> {
                    addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_VERIFICATION_WHATSAPP)
                }
                "TELEGRAM" -> {
                    addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_VERIFICATION_TELEGRAM)
                }
                else -> {
                    addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_VERIFICATION_TELEGRAM_BOT)
                }
            }
        }
    }

    /**
     * Telegram bot 校验，跳转链接
     */
    override fun showTiyendeCheckMobileTelegramBotLink(linkUrl: String) {
        val uri = Uri.parse(linkUrl)
        val intent = Intent(Intent.ACTION_VIEW, uri)
        startActivity(intent)
    }

    /**
     * 验证码发送成功
     * 当为YES时可以跳过，直接调用流程接口，根据流程步骤whatsappFlag标识走
     */
    override fun showTiyendeCheckMobileSendCodeSuccess(directLoginFlag: String) {
        hiddenTiyendeLoading()
        when(directLoginFlag){
            "YES" -> {
                showTiyendeCheckMobileSuccess()
            }
            else -> {
                startCountdownTimer()
            }
        }
    }

    /**
     * 需要选择出生日期
     */
    override fun showTiyendeCheckMobileChooseBirthdayDialog() {
        if(pvStartDateView == null){
            //时间可选范围18-100岁
            //当前日期
            val curtDate = Calendar.getInstance()
            val startDate = Calendar.getInstance()
            startDate.timeInMillis = curtDate.timeInMillis
            startDate.add(Calendar.YEAR,-100)

            val endDate = Calendar.getInstance()
            endDate.timeInMillis = curtDate.timeInMillis
            endDate.add(Calendar.YEAR,-18)

            pvStartDateView = TimePickerBuilder(this, object : OnTimeSelectListener {
                override fun onTimeSelect(date: Date?, v: View?) {
                }

                @SuppressLint("SimpleDateFormat")
                override fun onTimeSelectString(date: Date?, showDate: String?) {
                    val value = SimpleDateFormat("yyyy-MM-dd").format(date)
                    presenter?.onCheckNumberVerificationCodeAction(value)
                }
            })
                .setDate(endDate) //默认选中
                .setRangDate(startDate, endDate) //可选择时间范围
                .setLayoutRes(R.layout.tiyende_dialog_birthday) { v ->
//                    val ivClose = v?.findViewById<ImageView>(R.id.ivClose)
//                    ivClose.setOnClickListener {
//                        pvStartDateView?.dismiss()
//                    }
                    //确定
                    val btnDone = v.findViewById<TextView>(R.id.btnDone)
                    btnDone.setOnClickListener {
                        pvStartDateView?.returnData()
                        pvStartDateView?.dismiss()
                    }
                }
                .isDialog(true)
                .setContentTextSize(20)
                .setType(booleanArrayOf(true, true, true, false, false, false))
                .setLabel("", "", "", "", "", "")
                .setLineSpacingMultiplier(3.5f)
                .setTextXOffset(65, 65, 65, 65, 65, 65)
                .isCenterLabel(false)//是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setTextColorCenter(Color.parseColor("#FF3ED9AB")) //设置选中项文字颜色
                .setTextColorOut(Color.parseColor("#FFCBD5E1"))//默认颜色
                .setBgColor(Color.parseColor("#00000000"))
                .isAlphaGradient(true)
                .setItemVisibleCount(5)
                .isCyclic(true)
                .setDividerColor(ContextCompat.getColor(this, R.color.transparent))
                .build()
            val dialog = pvStartDateView?.dialog
            if (dialog != null){
                dialog.setCancelable(false)
                dialog.setCanceledOnTouchOutside(false)
                val dialogWindow = dialog.window
                if (dialogWindow != null) {
                    val params = dialogWindow.attributes
                    params.width = WindowManager.LayoutParams.MATCH_PARENT
                    params.height = WindowManager.LayoutParams.WRAP_CONTENT
                    dialogWindow.attributes = params
                    dialogWindow.setWindowAnimations(R.style.dialog_slide_anim) //修改动画样式
                    dialogWindow.setGravity(Gravity.BOTTOM)
                    dialogWindow.setDimAmount(0.3f)
                }
            }
        }
        pvStartDateView?.show()
    }


    /**
     * 校验成功
     */
    override fun showTiyendeCheckMobileSuccess() {
        TiyendeSharedHelper.addTiyendeSharedData(TiyendeSharedKey.TIYENDE_MOBILE, getTiyendeCheckMobile())
        publishEventData(TiyendeEventData(TiyendeEventData.TYPE.TIYENDE_PROCESS_REFRESH))
        if (countdownTimer != null){
            countdownTimer?.cancel()
        }
        finish()
    }

    /**
     * 发送成功提示
     */
    private fun showSendCodeSuccessDialog(){
        if (sendSuccessDialog == null){
            sendSuccessDialog = TiyendeCheckMobileSendCodeSuccessDialog(this)
            sendSuccessDialog?.setCancelable(true)
            sendSuccessDialog?.setCanceledOnTouchOutside(false)
        }
        sendSuccessDialog?.show()
        launch(Dispatchers.Main){
            delay(2000)
            sendSuccessDialog?.dismiss()
        }
    }

    /**
     * 提示dialog
     */
    private fun showTiyendeCheckMobileTipsDialog(){
        val tipsDialog = TiyendeTipsDialog(this)
        tipsDialog.setCancelable(true)
        tipsDialog.setCanceledOnTouchOutside(true)
        tipsDialog.show()
        tipsDialog.addTiyendeTipsEventRemark(eventRemark)
        tipsDialog.addTiyendeTitleText(getString(R.string.tiyende_dialog_notice))
        tipsDialog.addTiyendeTipsText(getString(R.string.tiyende_check_mobile_dialog_tips))
        tipsDialog.addTiyendeBtnOkText(getString(R.string.tiyende_check_mobile_dialog_understand))
        tipsDialog.isTiyendeDoubleButton(false)
    }

    /**
     * 提取连续的数字
     */
    private fun extractFirstNumber(input: String?): String? {
        if(input.isNullOrBlank()) return ""

        val regex = "\\d+".toRegex()
        return regex.find(input)?.value
    }

    class MyCountDownTimer(private val act: TiyendeCheckMobileActivity, millisInFuture: Int, countDownInterval: Long): CountDownTimer(millisInFuture.toLong(), countDownInterval) {
        override fun onTick(millisUntilFinished: Long) {
            // 这里每隔一段时间（定时器间隔）会被调用
            // 可以在这里更新UI，显示剩余时间
            act.countdown = (millisUntilFinished / 1000).toInt()
            act.showCheckCountdownText()
        }
        override fun onFinish() {
            // 倒计时完成时被调用
            act.showCheckCountdownComplete()
        }
    }

    /**
     * 倒计时
     */
    @SuppressLint("SetTextI18n")
    private fun showCheckCountdownText(){
        _binding?.btnSend?.text = "$countdown S"
    }

    /**
     * 倒计时完成
     */
    private fun showCheckCountdownComplete(){
        countdown = 60
        _binding?.btnSend?.text = getString(R.string.tiyende_button_send)
        _binding?.btnSend?.isEnabled = true
        isClickCheck = true
        showChcekMobileTypeView(false)
    }

    /**
     * 启动倒计时
     */
    @SuppressLint("SetTextI18n")
    private fun startCountdownTimer() {
        showSendCodeSuccessDialog()
        //随机 60秒 等待时长
        countdown = 60
        _binding?.btnSend?.text = "$countdown S"
        _binding?.btnSend?.isEnabled = false
        isClickCheck = false
        //手机号码输入框变成不可编辑状态
        _binding?.showMobileLayout?.visibility = View.VISIBLE
        _binding?.imgEdit?.visibility = View.INVISIBLE
        _binding?.showEditLayout?.visibility = View.GONE

        if (countdownTimer == null){
            countdownTimer = MyCountDownTimer(this, countdown * 1000, 1000)
        }
        countdownTimer?.start()
    }

    override fun onTiyendePublishEvent(event: TiyendeEventData) {
        super.onTiyendePublishEvent(event)
        when(event.eventType){
            TiyendeEventData.TYPE.TIYENDE_PROCESS_REFRESHED -> {
                hiddenTiyendeLoading()
                //需要校验 WhatsApp 或 SMS || telegram || telegramBot
                if (!TiyendeProcessHelper.isTiyendeAuthenticationCheckMobile()){
                    //校验成功
                    showTiyendeCheckMobileSuccess()
                }
            }
            else -> {

            }
        }
    }

    override fun hiddenTiyendeLoading() {
        super.hiddenTiyendeLoading()
        _binding?.checkRefreshLayout?.isRefreshing = false
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(TiyendeEventPointType.PAGE.TIYENDE_PAGE_VERIFICATION_SMS_START, eventRemark)
        presenter?.let {
            val checkType = it.getCheckNumberSelectType()
            if (checkType == "TGBOT"){
                //需要调流程接口查询校验结果
                publishEventData(TiyendeEventData(TiyendeEventData.TYPE.TIYENDE_PROCESS_REFRESH))
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(TiyendeEventPointType.PAGE.TIYENDE_PAGE_VERIFICATION_SMS_END, eventRemark)
        if (countdownTimer != null){
            countdownTimer?.cancel()
            countdownTimer = null
        }
        if (smsBroadcastReceiver != null){
            unregisterReceiver(smsBroadcastReceiver)
        }
    }
}